// 历史房间页面逻辑
const app = getApp()

Page({
  data: {
    userInfo: null,
    userStats: {
      winCount: 0,
      lossCount: 0,
      totalScore: 0,
      winRate: 0
    },
    roomHistory: [],
    loading: true,
    adConfig: {
      enabled: true
    }
  },

  onLoad() {
    console.log('历史房间页面加载')
    this.loadUserInfo()
    this.loadRoomHistory()
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadRoomHistory()
  },

  // 加载用户信息
  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      })
    }
  },

  // 加载历史房间数据
  loadRoomHistory() {
    this.setData({ loading: true })

    wx.request({
      url: `${app.globalData.baseUrl}/api/accounting/user-room-history`,
      method: 'GET',
      data: {
        user_id: this.data.userInfo?.id
      },
      success: (res) => {
        console.log('历史房间数据:', res.data)
        
        if (res.data.success) {
          const data = res.data.data
          
          // 更新用户统计
          this.setData({
            userStats: {
              winCount: data.winCount || 0,
              lossCount: data.lossCount || 0,
              totalScore: data.totalScore || 0,
              winRate: data.winRate || 0
            }
          })

          // 处理房间历史数据，按年份分组
          const roomHistory = this.groupRoomsByYear(data.rooms || [])
          this.setData({
            roomHistory: roomHistory
          })
        } else {
          console.error('获取历史房间失败:', res.data.message)
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('请求历史房间数据失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
      }
    })
  },

  // 按年份分组房间数据
  groupRoomsByYear(rooms) {
    const yearGroups = {}
    
    rooms.forEach(room => {
      const year = new Date(room.created_at).getFullYear()
      if (!yearGroups[year]) {
        yearGroups[year] = []
      }
      yearGroups[year].push(room)
    })

    // 转换为数组并按年份倒序排列
    return Object.keys(yearGroups)
      .sort((a, b) => parseInt(b) - parseInt(a))
      .map(year => ({
        year: parseInt(year),
        rooms: yearGroups[year].sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
      }))
  },

  // 格式化房间数据
  formatRoomData(room) {
    const date = new Date(room.created_at)
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return {
      id: room.id,
      room_code: room.room_code,
      date: `${month}-${day}`,
      time: `${hours}:${minutes}`,
      score: room.final_score || 0,
      result: (room.final_score || 0) >= 0 ? 'win' : 'loss',
      opponent_name: room.opponent_name || '未知',
      opponent_score: room.opponent_score || 0,
      tea_score: room.tea_score || 0,
      created_at: room.created_at
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadRoomHistory()
    wx.stopPullDownRefresh()
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 查看房间详情
  viewRoomDetail(e) {
    const roomId = e.currentTarget.dataset.roomId
    if (roomId) {
      wx.navigateTo({
        url: `/pages/room-settlement/room-settlement?room_id=${roomId}`
      })
    }
  }
})